<template>
  <div>
    <el-upload
    class="upload-demo"
    drag
    action="https://upload-z2.qiniup.com"
    :data="postData"
    :on-success="handleAvatarSuccess"
    multiple>
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  data () {
    return {
      postData: {
        token: '-wB7gbMbeR_0yOZ_Pige0M_YtUHPTBsggN6fj6lB:AMotC9cCSiJWsGcu_4QgmF-PMVQ=:eyJzY29wZSI6InF0ZXN0YnVja2V0IiwiZGVhZGxpbmUiOjE1MjAzNDcxMTl9'
      },
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess (res, file) { // 上传成功后在图片框显示图片
      this.imageUrl = 'http://p24hjnsdi.bkt.clouddn.com/' + res.key
      console.log(res)
    },
    handleError (res) { // 显示错误
      console.log(res)
    },
    beforeAvatarUpload (file) { // 在图片提交前进行验证
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isPNG && isLt2M
    }
  }
}
</script>

<style scoped lang="stylus" rle="stylesheet/stylus">
</style>
